package com.lheia.jcb.spider

import com.lheia.util.PageFieldConstants
import grails.gorm.transactions.Transactional
import org.grails.datastore.gorm.GormEntity
import us.codecraft.webmagic.ResultItems
import us.codecraft.webmagic.Task
import us.codecraft.webmagic.pipeline.Pipeline

@Transactional
class PipelineService implements Pipeline{

    def save(ResultItems resultItems, Task task){
        def clazz = resultItems.get(PageFieldConstants.DOMAIN_CLASS)
        def resData = resultItems.get(PageFieldConstants.RESULT_DATA)
        if(!resData){
            log.info("无数据保存")
            return
        }
        if(clazz){
            if(resData instanceof List){
                resData.each {
                    def domainInstance = clazz.newInstance()
                    GormEntity gormEntity = (GormEntity)domainInstance
                    gormEntity.properties = it
                    gormEntity.save(flush:true,failOnError:true)
                }
            }else(resData instanceof Map){
                def domainInstance = clazz.newInstance()
                GormEntity gormEntity = (GormEntity)domainInstance
                gormEntity.properties = resData
                gormEntity.save(flush:true,failOnError:true)
            }
        }else{
            if(resData instanceof List){
                resData.each {
                    it.save(flush:true,failOnError:true)
                }
            }else{
                resData.save(flush:true,failOnError:true)
            }
        }
    }
/**
 * Process extracted results.
 *
 * @param resultItems resultItems
 * @param task task
 */

    @Override
    void process(ResultItems resultItems, Task task) {

    }
}
